package de.szut.scene.helper;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.drawable.PictureDrawable;
import android.util.Log;
import de.szut.database.DatabaseHelper;
import de.szut.entity.Country;
import de.szut.util.Settings;
import org.andengine.extension.svg.SVGParser;
import org.andengine.extension.svg.adt.SVG;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;

/**
 * Created with IntelliJ IDEA.
 * User: nbothmer
 * Date: 02.10.13
 * Time: 12:59
 * To change this template use File | Settings | File Templates.
 */
public class GameMapHelper {

    private static GameMapHelper INCTANCE = null;

    private boolean isPixelCalculationCompleted = false;

    private HashMap<String, ArrayList<String>> countryMap = new HashMap<String, ArrayList<String>>();
    private HashMap<Integer, ArrayList<String>> colorToCoordinateMap = new HashMap<Integer, ArrayList<String>>();
    private HashMap<String,String> countryCenterPoints = new HashMap<String, String>();
    private Bitmap backgroundBitmap;

    public static GameMapHelper getInctance() {
        if (INCTANCE == null) {
            INCTANCE = new GameMapHelper();
        }
        return INCTANCE;
    }

    public Bitmap getGameMapAsBitmap(AssetManager assetManager) {

        try {
            SVG svg = SVGParser.parseSVGFromAsset(assetManager, "gfx/game/" + Settings.GAME_SCREEN_CLICK);
            Picture p = svg.getPicture();
            PictureDrawable pd = new PictureDrawable(p);
            backgroundBitmap = Bitmap.createBitmap(pd.getIntrinsicWidth(), pd.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(backgroundBitmap);
            canvas.drawPicture(pd.getPicture());
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return backgroundBitmap;
    }

    public boolean calculateMapsPixel(Bitmap backgroundBitmap, DatabaseHelper dbHelper) {
        List<Country> countries = null;
        try {
            countries = dbHelper.getCountryDao().queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        if (countries != null) {
            for (int k = 0; k < countries.size(); k++) {
                ArrayList<String> coordinates = new ArrayList<String>();
                Country country = countries.get(k);
                for (int x = 0; x < backgroundBitmap.getWidth(); x++) {
                    for (int y = 0; y < backgroundBitmap.getHeight(); y++) {
                        int color = backgroundBitmap.getPixel(x, y);
                        if (color == country.getColor()) {
                            coordinates.add(Integer.toString(x) + ";" + Integer.toString(y));
                        }
                        y++;
                    }
                    x++;
                }
                calculateCountryCenterPoint(country,coordinates);
                countryMap.put(country.getName(), coordinates);

            }
        }

        return !countryMap.isEmpty();
    }

    public void calculateCountryCenterPoint(Country country,ArrayList<String> coordinates) {
        String centerPoint;
        ArrayList<Integer> xValues = new ArrayList<Integer>();
        ArrayList<Integer> yValues = new ArrayList<Integer>();
        for (String s : coordinates) {
            StringTokenizer tokenizer = new StringTokenizer(s, ";");
            int x = Integer.parseInt(tokenizer.nextToken());
            int y = Integer.parseInt(tokenizer.nextToken());
            xValues.add(x);
            yValues.add(y);
        }
        centerPoint = Integer.toString(calculateCenterPoint(xValues)) + ";" + Integer.toString(calculateCenterPoint(yValues));
        Log.d("1337_test", country.getName()+"_:_"+centerPoint);
        countryCenterPoints.put(country.getName(),centerPoint);
    }
    public int calculateCenterPoint(ArrayList<Integer> value){
        int center;
        int total=0;
        for(int i : value ){
            total += i;
        }
        center = total/value.size();
        return center;
    }

    // copy whole method (replace it)
    public boolean test(Bitmap backgroundBitmap, DatabaseHelper dbHelper) {
        List<Country> countries = null;
        try {
            countries = dbHelper.getCountryDao().queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        if (countries != null) {
            this.calculateColorsToCoordinates(backgroundBitmap);
            for (Country country : countries) {
                countryMap.put(country.getName(), this.getCoordinatesByColor(country.getColor()));

            }
        }

        return !countryMap.isEmpty();
    }

    // copy whole method
    private ArrayList<String> getCoordinatesByColor(int color) {
        return this.colorToCoordinateMap.get(color);
    }

    // copy whole method
    private void calculateColorsToCoordinates(Bitmap backgroundBitmap) {
        // guess there is no reason to reload this map at any time
        if (this.colorToCoordinateMap.isEmpty()) {
            for (int x = 0; x < backgroundBitmap.getWidth(); x++) {
                for (int y = 0; y < backgroundBitmap.getHeight(); y++) {
                    int color = backgroundBitmap.getPixel(x, y);
                    if (!this.colorToCoordinateMap.containsKey(color)) {
                        this.colorToCoordinateMap.put(color, new ArrayList<String>());
                    }
                    this.colorToCoordinateMap.get(color).add(Integer.toString(x) + ";" + Integer.toString(y));
                }
            }
        }
    }

    public HashMap<String, ArrayList<String>> getCountryMap() {
        return countryMap;
    }

    public HashMap<String, String> getCountryCenterPoints() {
        return countryCenterPoints;
    }

    public boolean isPixelCalculationCompleted() {
        return isPixelCalculationCompleted;
    }

    public void setPixelCalculationCompleted(boolean pixelCalculationCompleted) {
        isPixelCalculationCompleted = pixelCalculationCompleted;
    }

    public Bitmap getBackgroundBitmap() {
        return backgroundBitmap;
    }
}
